$(function () {
    let mixPay = false
    let money = 0
    $.ajax({
        url:orderUrl.searchUserOrderList,
        type:"post",
        dataType:"json",
        contentType: "application/json",
        //beforeSend:提交请求前执行
        beforeSend: function (request) {
            request.setRequestHeader("token",localStorage.getItem("token"));
        },
        data:JSON.stringify({
            "page":1,
            "length":20
        }),
        success: function (resp) {
            if(resp.code == 0){
                // console.log(resp)
                let list = resp.list
                let temp = ''
                for(let one of list){
                    let status = one.status
                    if(status==1){
                        one.status = "未付款"
                    }else if(status==2){
                        one.status = "已付款"
                    }else if(status==3){
                        one.status = "已发货"
                    }else if(status==4){
                        one.status = "已签收"
                    }
                    let button = ''
                    if(one.status=="未付款"){
                        button = '<input type="button" value="支付" class="pay-btn" />'
                    }
                    temp += `
                        <div class="order" data-order-id = "${one.id}">
                            <div class="row row-1">
                                <span>订单编号：${one.code}</span>
                                <span>${one.status}</span>
                            </div>
                            <div class="row row-2">
                                假设这里是商品订单概要信息
                            </div>
                            <div class="row row-3">
                                <div>
                                    订单金额：<span style="color:#9e04de" name="amount">${one.amount}</span>元
                                </div>
                            </div>`
                            if(one.status=="未付款"){
                             temp +=
                            `<div class="row row-3">
                                <div>
                                    账户余额：<span style="color:#9e04de" name="amt">${one.amt}</span>元
                                </div>`
                                if(one.amt>0){
                                    temp +=
                                    `<div>
                                        使用余额付款：
                                        <input type="checkbox" name="useBalance" value="true"/>
                                    </div>`
                                }
                              temp +=`</div>`
                            }
                            temp +=
                            `<div class="row">
                                ${button}
                            </div>      
                        </div>   
                    `
                }
                //更新加载订单页数据
                $(".order-list").append(temp)

                //支付按钮点击事件
                $(".pay-btn").click(function () {
                    let orderElement = $(this).parents(".order")
                    let orderId = orderElement.data("order-id")
                    let amount = orderElement.find("[name='amount']").text()
                    let amt = orderElement.find("[name='amt']").text()
                    if(amt>0){
                        let useBalance = orderElement.find("[name='useBalance']")[0].checked
                        if(useBalance){

                            if(amt>=amount){
                                /** 用余额支付 */
                                $.ajax({
                                    url: orderUrl.useBalancePay,
                                    type: "post",
                                    dataType: "json",
                                    contentType: "application/json",
                                    //beforeSend:提交请求前执行
                                    beforeSend: function (request) {
                                        request.setRequestHeader("token", localStorage.getItem("token"));
                                    },
                                    data: JSON.stringify({
                                       "orderId":orderId
                                    }),
                                    success: function (resp) {
                                        if(resp.msg=="付款成功"){
                                            location.href = "order.html"
                                        }
                                    }
                                })
                            }else{
                                /** 融合支付*/
                                alert("余额不足，将改成融合支付模式")
                                mixPay = true
                                //充值的金额
                                money = amount-amt
                                $(".payment-list").attr("data-order-id",orderId)
                                $(".select-payment").show()
                            }
                        }else{
                            $(".payment-list").attr("data-order-id",orderId)
                            $(".select-payment").show()
                        }
                    }else{
                        $(".payment-list").attr("data-order-id",orderId)
                        $(".select-payment").show()
                    }


                })
            }
        }
    })

    /**
     * 获取url参数
     * @param name
     * @returns {string|null}
     */
    function getUrlParam(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]); return null;
    }

    //拿到商品订单的流水号
    let code = getUrlParam('out_trade_no')
    if(code != null && code != ''){
        $.ajax({
            url:zfbUrl.updateNativeOrderStatus,
            type:"post",
            dataType:"json",
            contentType:"application/json",
            beforeSend: function (request) {
                request.setRequestHeader("token",localStorage.getItem("token"));
            },
            data:JSON.stringify({
                "code":code,
            }),
            success: function (resp) {
                if(resp.msg=="订单状态已修改"){
                    location.href = "order.html"
                }
            }
        })
    }

    /**
     * 点击面板就隐藏
     */
    $(".select-payment").click(function(){
        $(this).hide()
    })

    /**
     * 阻止事件向上冒泡
     */
    $(".payment-list").click(function(e){
        e.stopPropagation()
    })

    /**
     * XX支付的点击事件
     */
    $(".payment-item").click(function () {
        $(".select-payment").hide()
        let orderId = $(this).parents(".payment-list").data("order-id")
        let payment = $(this).data("payment")
        if(payment == 'wxpay'){
            $.ajax({
                url:wxUrl.nativePayOrder,
                type:"post",
                dataType: "json",
                contentType: "application/json",
                beforeSend: function (request) {
                    request.setRequestHeader("token",localStorage.getItem("token"));
                    request.setRequestHeader("ip",localStorage.getItem("ip"));
                },
                data:JSON.stringify({
                    "orderId":orderId
                }),
                success:function (resp) {
                    if(resp.code==0){
                        let codeUrl = resp.codeUrl
                        // console.log(codeUrl)
                        $(".qrCode").attr("src",wxUrl.qrCode+"?codeUrl="+codeUrl)
                        //手动点击确认【完成付款】需要用到orderId查询付款结果，所以自定义属性并把orderId赋值方便判断支付结果
                        $(".close-btn").attr("data-order-id",orderId)
                        $("#native").show()

                        /** 执行定时函数查询支付结果 */
                        let num = 0
                        //setInterval: 循环定时器
                        let timer = setInterval(function(){
                            num++
                            let result = searchOrderStatus(orderId)
                            if(result){
                                //支付成功,取消定时器
                                clearInterval(timer)
                                //刷新页面
                                location.reload()
                            }else if(num==10){
                                clearInterval(timer)
                            }
                        },5000)
                    }
                }
            })
        }
        else if(payment == 'alipay'){
            $.ajax({
                url:zfbUrl.nativePayOrder,
                type:"post",
                dataType: "json",
                contentType: "application/json",
                beforeSend: function (request) {
                    request.setRequestHeader("token",localStorage.getItem("token"));
                    request.setRequestHeader("ip",localStorage.getItem("ip"));
                },
                data:JSON.stringify({
                    "orderId":orderId
                }),
                success:function (resp) {
                    if(resp.code==0){
                        let htmlCode = resp.htmlCode
                        console.log(htmlCode)
                        $("#htmlCode").html(htmlCode)
                    }
                }
            })
        }
        else if(payment == 'unpay'){
            let url;
            if(mixPay){
                //银联融合支付
                url = unionUrl.mixPay
            }else{
                //银联native支付
                url = unionUrl.nativePayOrder
            }
            $.ajax({
                url:url,
                type:"post",
                dataType: "json",
                contentType: "application/json",
                beforeSend: function (request) {
                    request.setRequestHeader("token",localStorage.getItem("token"));
                    request.setRequestHeader("ip",localStorage.getItem("ip"));
                },
                data:JSON.stringify({
                    "orderId":orderId,
                    "money": money
                }),
                success:function (resp) {
                    if(resp.code==0){
                        let htmlCode = resp.htmlCode
                        console.log(htmlCode)
                        $("#htmlCode").html(htmlCode)
                    }
                }
            })
        }
    })

    /**
     * 封装【查询支付结果】方法
     * @param orderId
     * @returns {boolean}
     */
    function searchOrderStatus(orderId){
        let flag = false
        $.ajax({
            url: wxUrl.searchOrderStatus,
            type:"post",
            dataType: "json",
            contentType: "application/json",
            async:false, //设置为同步执行
            beforeSend: function (request) {
                request.setRequestHeader("token",localStorage.getItem("token"));
            },
            data:JSON.stringify({
                "orderId":orderId
            }),
            success:function(resp){
                if(resp.msg == "订单状态已修改"){
                    flag = true
                }
            }
        })
        return flag
    }

    /**
     * 50秒之后才扫码支付，就只能手动点击【完成】刷新页面
     */
    $(".close-btn").click(function(){
        let orderId = $(this).data("order-id")
        let result = searchOrderStatus(orderId)
        if(result){
            location.reload()
        }
    })

    /**
     * 隐藏支付二维码弹框
     */
    $(".close-icon").click(function(){
        $("#native").hide()
    })

})